<template>
  <MainSlot :show-btn-box="false">
    <template v-slot:searchForm>
      <SearchForm :formItemList="formItemList" @search="search"></SearchForm>
    </template>
    <template v-slot:table>
      <div class="weather">
        <!-- <img :src="weatherData.icon" alt=""> -->
        <span>天气： {{ weatherData.weather }}</span>
        <span>风向： {{ weatherData.winddirection }}</span>
        <span>风力： {{ weatherData.windpower }}</span>
        <span>温度： {{ weatherData.temperature }}°C</span>
        <span>湿度： {{ weatherData.humidity }}%RH</span>
      </div>
      <div class="checkbox-box">
        <el-checkbox-group v-model="checkList">
          <el-checkbox label="视频监控设备"></el-checkbox>
          <el-checkbox label="环境监测设备"></el-checkbox>
          <el-checkbox label="气象监测设备"></el-checkbox>
          <el-checkbox label="远程控制设备"></el-checkbox>
        </el-checkbox-group>
      </div>
      <baidu-map class="map" :center="center" :zoom="zoom" :scroll-wheel-zoom="true" map-type="BMAP_HYBRID_MAP">
        <bm-navigation anchor="BMAP_ANCHOR_TOP_RIGHT" />
        <BmlMarkerClusterer :average-center="true">
          <bm-marker v-for="(item, index) in groupLngLatArr" :key="index + 9999999999" :position="{
            lng: item.center.lng - 0.000003,
            lat: item.center.lat - 0.000043,
          }" :dragging="false" :icon="{ url: 'none', size: { width: 0, height: 0 } }">
            <bm-label :content="item[0].title.facilityName" :label-style="labelStyle"
              :offset="{ width: -5, height: 15 }" @click="infoMultipleOpen(item)" />
          </bm-marker>
          <template v-if="checkList.includes('视频监控设备')">
            <bm-marker v-for="(item, index) in groupLngLatArr" :key="index + 9999999999999" :position="{
              lng: item.center.lng - 0.000003,
              lat: item.center.lat + 0.00007,
            }" :dragging="false"
              :icon="{ url: 'https://matefarm.net/file/img/chenglong_6.png', size: { width: 30, height: 30 } }"
              @click="caremaOpen(item)">
              <bm-label :content="`监控数量:${cameraCount[item.facilityNo] || '-'}`" :label-style="labelStyle"
                :offset="{ width: 0, height: 25 }" @click="caremaOpen(item)" />
            </bm-marker>
          </template>
          <template v-for="(item, index) in deviceList">
            <bm-marker v-if="checkList.includes(checkObj[item.deviceType])" :key="index + 99999999999999" :position="{
              lng: item.axisX,
              lat: item.axisY,
            }" :offset="{ width: 10, height: 6 }" :dragging="false" :icon="{
              url: getImage(item.deviceType),
              size: getSize(item.deviceType)
            }" @click="deviceOpen(item)">
              <bm-label :content="item.deviceName" :label-style="labelStyle" :offset="getOffset(item.deviceType)"
                @click="deviceOpen(item)" />
            </bm-marker>
          </template>
          <template v-if="checkList.includes('虫情监测设备')">
            <bm-marker v-for="(item, index) in pestList" :key="index + 9999999999999999" :position="{
              lng: item.longitude,
              lat: item.latitude,
            }" :offset="{ width: 10, height: 6 }" :dragging="false" :icon="{
              url: 'https://matefarm.net/file/img/chenglong_1.png',
              size: { width: 50, height: 50 }
            }" @click="pestOpen(item)">
              <bm-label :content="item.deviceName" :label-style="labelStyle" :offset="{ width: 0, height: 35 }"
                @click="pestOpen(item)" />
            </bm-marker>
          </template>
        </BmlMarkerClusterer>
        <!-- 虫情测报站基本信息 -->
        <bm-info-window :position="{ lng: pestPint.longitude, lat: pestPint.latitude }" :show="pestInfoShow"
          :offset="{ width: -25, height: -5 }" :width="25" @close="pestInfoShow = false">
          <p class="BMap_bubble_title">基本信息</p>
          <p class="BMap_bubble_title">{{ insectData[`${pestPint.insectDeviceId}time`] }}</p>
          <p>有效半径：500m</p>
          <p :style="{ color: getPestStyle(insectData[pestPint.insectDeviceId]) }">
            虫害风险等级：{{ getRisk(insectData[pestPint.insectDeviceId]) }}
          </p>
          <!-- <p>螟虫：7（低风险）</p> -->
        </bm-info-window>
        <template v-for="(item, index) in pestList">
          <bm-circle v-if="!item.radius && insectData[item.insectDeviceId] > 0" :center="{
            lng: item.longitude,
            lat: item.latitude,
          }" :radius="item.radius || 500" stroke-color="transparent" :stroke-opacity="0.5" :stroke-weight="1"
            :fill-color="getPestStyle(insectData[item.insectDeviceId])" :fill-opacity="0.3"></bm-circle>
        </template>
        <!-- 环境监测基本信息 -->
        <bm-info-window :position="{ lng: devicePint.axisX, lat: devicePint.axisY }" :show="deviceInfoShow"
          :offset="{ width: -5, height: -5 }" :width="330" @close="deviceInfoShow = false">
          <p class="BMap_bubble_title">基本信息</p>
          <p class="BMap_line" v-for="item, i in deviceIotList" :key="i">
            <span class="BMap_line_title">{{ item.dataItemName }}： {{ item.lastValue1 }}{{ item.symbol || '' }}</span>
            <span class="BMap_line_time">{{ item.collectDatetime }}</span>
          </p>
          <!-- <p v-if="!deviceIotList.length" class="center">暂无环境数据</p> -->
          <p v-if="deviceBtnList.length > 0" class="control-title">远程控制</p>
          <el-carousel class="control-box" height="120px" indicator-position="none" arrow="always" :autoplay="false"
            v-if="deviceBtnList.length > 0">
            <el-carousel-item class="zh-contro" v-for="ite in deviceBtnList" :key="ite.dataItemId">
              <div class="contro-one">
                <div class="contro-one-title">{{ ite.dataItemName }}</div>
                <div class="contro-one-stau" :style="{ color: getequipmentStyle(ite.nowstau) }">{{ ite.nowstau }}</div>
              </div>
              <div v-if="ite.enumListTypetwo && ite.enumListTypetwo.length > 0" class="contro-two">
                <div v-for="(
                    kaiguanitem, kaiguanindex
                  ) in ite.enumListTypetwo" :key="kaiguanindex"
                  :class="{ 'contro-two-zcon': judgePermission(2, 'remoteControl') === true, 'contro-two-zcon-disabled': judgePermission(2, 'remoteControl') === false }"
                  @click="judgePermission(2, 'remoteControl') ?
                    controlequpmentone(ite.dataItemId, kaiguanitem.value, kaiguanindex)
                    : $message.warning('暂无权限')">
                  {{ kaiguanitem.name }}
                </div>
              </div>
              <div v-else class="contro-two">
                <el-input-number v-model="ite.enumListValue" controls-position="right" :min="0" class="inputnumber" />
                <div v-if="ite.dataTypeId == '193'" class="unit">kg</div>
                <div class="contro-two-zcon" @click="controlequpmentone(ite.dataItemId, ite.enumListValue)">
                  {{ '启动' }}
                </div>
              </div>
            </el-carousel-item>
          </el-carousel>
        </bm-info-window>

        <bm-info-window :position="{ lng: lngLatCore.lng, lat: lngLatCore.lat }" :show="infoWindow.show"
          @close="infoWindowClose">
          <p class="BMap_bubble_title">设施信息</p>
          <p><span>设施类型:</span> {{ lngLatArrform.facilityTypeName }}</p>
          <p><span>设施组:</span> {{ lngLatMultipleform.groupName }}</p>
          <p><span>设施名称:</span> {{ lngLatArrform.facilityName }}</p>
          <p><span>承租户:</span> {{ lngLatArrform.lesseeName }}</p>
          <p><span>农业类型:</span> {{ lngLatArrform.farmingTypeName }}</p>
          <!-- <p><span>种植品种:</span> {{ lngLatArrform.plantingTypeName }}</p> -->
          <p><span>地址:</span> {{ lngLatArrform.address }}</p>
          <p><span>面积: </span> {{ lngLatArrform.scope }} 亩</p>
        </bm-info-window>
        <bm-polygon :path="lngLatArr" stroke-color="#ffdb5c" fill-color="transparent" :stroke-opacity="1"
          :fill-opacity="0.4" :stroke-weight="3" :editing="jkedit" @click="infoWindowOpen(lngLatArr)"
          @mouseout="infoWindowOot" />
        <div v-for="(item, index) in groupLngLatArr" :key="index">
          <bm-polygon :path="item" stroke-color="#03F5EC" fill-color="transparent" :stroke-opacity="1"
            :fill-opacity="0.2" :stroke-weight="3" :editing="jkedit" @click="infoMultipleOpen(item)"
            @mouseout="infoMultipleOut" />
        </div>
        <bm-info-window :position="{
          lng: lngLatMultipleCore.lng,
          lat: lngLatMultipleCore.lat,
        }" :show="infoMultiple.show" @close="infoMultipleClose">
          <p class="BMap_bubble_title">设施信息</p>
          <p>
            <span>设施类型:</span> {{ lngLatMultipleform.facilityTypeName }}
          </p>
          <p><span>设施组:</span> {{ lngLatMultipleform.groupName }}</p>
          <p><span>设施名称:</span> {{ lngLatMultipleform.facilityName }}</p>
          <p><span>承租户:</span> {{ lngLatMultipleform.lesseeName }}</p>
          <!-- <p><span>农业类型:</span> {{ lngLatMultipleform.farmingTypeName }}</p> -->
          <p>
            <span>种植品种:</span>
            {{ lngLatMultipleform.plantingTypeName }}
          </p>
          <p><span>地址:</span> {{ lngLatMultipleform.address }}</p>
          <p><span>面积: </span>{{ lngLatMultipleform.scope }} 亩</p>
        </bm-info-window>
      </baidu-map>
    </template>
    <template v-slot:dialogModule>
      <el-dialog class="camera-dialog" title="视频监控" :visible.sync="isShowCamera" @close="isShowCamera = false">
        <cameraDialog ref="cameraDialog" :cameralistparam="cameralistparam" :isShowCamera="isShowCamera" />
      </el-dialog>
      <el-dialog title="输入验证码" :visible.sync="yanzhengcodeview" width="30% !important" class="yanzheng">
        <div class="dig-yanzhencode">
          <div>
            <img :src="nowcodeimg" />
            <div class="changecodeimg" @click="openyanzhencode()">看不清换一张</div>
          </div>
          <el-input v-model="nowcodetwo" placeholder="请输入验证码" />
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button type="success" @click="yanzhengcodeview = false">取消</el-button>
          <el-button type="primary" @click="yanzhengcode()">确认执行</el-button>
        </span>
      </el-dialog>
    </template>
  </MainSlot>
</template>

<script>
import SearchForm from '@/components/SearchForm';
import MainSlot from "@/components/MainSlot";
import landgroupInfoManage from "@/api/digital-operation/land-manage/land-group-manage";
import divideInfoManage from "@/api/digital-operation/land-manage/divide-manage";
import tenantInfo from "@/api/digital-operation/tenant-manage/tenant-info/index";
import nowpagereq from "@/api/basic-info-manage/camera-management/index";//1
import pestApi from "@/api/basic-info-manage/pest-equipment-management/index";
import deviceApi from "@/api/basic-info-manage/device-allocation-data";
import insectApi from "@/api/digital-production/pest-management/insect-alert"
// import nowuserpagereq from "@/api/user/index";
import cameraDialog from "./component/cameraDialog";
// import { mymixin } from "@/utils/mixin";
// import SearchBox from "@/components/SearchBox";
import { BmlMarkerClusterer } from "vue-baidu-map";
import { mapGetters } from "vuex";
import axios from 'axios';
export default {
  name: "DivideInfo",
  components: {
    SearchForm,
    MainSlot,
    // SearchBox,
    BmlMarkerClusterer,
    cameraDialog
  },
  // mixins: [mymixin],
  data() {
    return {
      unfoldFlag: false,
      checkList: [
        // "视频监控设备", "环境监测设备", "虫情监测设备", "气象监测设备", "远程控制设备"
        "视频监控设备", "环境监测设备", "气象监测设备", "远程控制设备"
      ],
      checkObj: {
        '大田杆': '环境监测设备',
        '光伏大田杆': '环境监测设备',
        '水质杆': '环境监测设备',
        '气象站': '气象监测设备',
        '集中器': '远程控制设备',
      },
      formItemList: [
        {
          label: '设施组',
          type: 'select',
          selectOptions: this.setOptions('facilityGroupNo'),
          param: 'facilityGroupNo',
          defaultSelect: '',
          multiple: false,
          isShow: true
        },
        {
          label: '设施',
          type: 'select',
          selectOptions: this.setOptions('facilityNo'),
          param: 'facilityNo',
          defaultSelect: '',
          multiple: false,
          isShow: true
        }
      ],
      searchlist: {},
      isShowCamera: false,
      cameralistparam: {},
      // 是否可修改
      jkedit: false,
      // 地图相关值
      center: { lng: 120.230648, lat: 30.811543 },
      zoom: 17,
      keyword: "",
      polyline: {
        editing: false,
        paths: []
      },
      groupLngLatArr: [],
      // 经纬度数组
      lngLatArr: [],
      // 设施数组
      facilityArr: [],
      // 设施组数组
      facilityGroupArr: [],
      input2: "",
      facilityNo: "", // 查询条件设施ID
      facilityGroupNo: "", // 查询条件设施组Id
      infoWindow: {
        show: false
      },
      labelStyle: {
        color: "#fffff0",
        fontSize: "12px",
        borderRadius: "11px",
        border: "none",
        backgroundColor: "#0492FC",
        padding: "3px 6px",
        opacity: ".8",
        letterSpacing: "2px",
        transform: "translateX(-32%)"
      },
      lesseeList: [],
      lesseeNo: "",
      lngLatArrform: {},
      lngLatCore: {},
      infoMultiple: {
        show: false
      },
      facilityGName: "",
      lngLatMultipleform: {},
      lngLatMultipleCore: {},
      // 环境监测设备
      deviceList: [],
      devicePint: {},
      deviceInfoShow: false,
      deviceIotList: [],
      deviceBtnList: [],
      // 虫报站
      pestList: [],
      pestPint: {},
      pestInfoShow: false,
      pestIotList: [],
      insectData: {},
      // 气象监测设备
      meteorologyList: [],
      meteorologyPint: {},
      meteorologyInfoShow: false,
      meteorologyIotList: [],
      // 验证码弹框
      yanzhengcodeview: false,
      // 验证码
      nowcode: "",
      // 验证码图片
      nowcodeimg: "",
      nowcodetwo: "",
      // 临时存储的设备开关信息
      nowcontrolmessage: {
        zhid: "",
        zhkey: "",
        zhindex: ""
      },
      weatherData: {},
      cameraCount: {},
    };
  },
  watch: {},
  computed: {
    ...mapGetters({
      judgePermission: "permission/judgePermission"
    }),
  },
  mounted() {
    this.$nextTick(() => {
      // 条件查询所有设施组信息
      this.queryFacilityGroupList();
      // 条件查询所有设施信息
      this.getFacilityListByConditionAll();
      // 查询所有设施信息
      this.FacilityPointList();
      this.querylesseeList()
    });
  },
  created() {
    // this.queryWeather()
    this.queryCameraCount()
    this.getInsectDevice()
    this.queryDevice()
    if (sessionStorage.organizationNo === "WUSHI") {
      // this.center = { lng: 119.775106, lat: 30.978951 }
      // this.$set(this.center, 'lng', 120.340248)
      // this.$set(this.center, 'lat', 30.898158)
    }
  },
  // beforeDestroy() {
  //   if (this.timer) {
  //     clearInterval(this.timer);
  //   }
  // },
  methods: {
    setOptions(param) {
      let options = [];
      if (param == 'stordocNo') {
        this.$store.state.initData.stordoc.forEach(item => {
          options.push(
            { text: item.stordocName, value: item.stordocNo }
          )
        })
      } else if (param == 'facilityNo') {
        this.$store.state.initData.allFacility.forEach(item => {
          options.push(
            { text: item.facilityName, value: item.facilityNo }
          )
        })
      } else if (param == 'lesseeNo') {
        console.log(this.$store.state.initData.lessesList)
        this.$store.state.initData.lessesList.forEach(item => {
          options.push(
            { text: item.lesseeName, value: item.lesseeNo }
          )
        })
      } else if (param == 'facilityGroupNo') {
        console.log(this.$store.state.initData.facilityGroup)
        this.$store.state.initData.facilityGroup.forEach(item => {
          options.push(
            { text: item.facilityGroupName, value: item.facilityGroupNo }
          )
        })
      }
      return options;
    },
    getImage(type) {
      if (type === "大田杆" || type === "光伏大田杆") {
        return "https://matefarm.net/file/img/chenglong_8.png";
      }
      if (type === "水质杆") {
        return "https://matefarm.net/file/img/chenglong_7.png";
      }
      if (type === "气象站") {
        return "https://matefarm.net/file/img/chenglong_9.png";
      }
      if (type === "集中器") {
        return "https://matefarm.net/file/img/chenglong_10.png";
      }
    },
    getSize(type) {
      if (type === "大田杆" || type === "光伏大田杆") {
        return { width: 36, height: 87 };
      }
      if (type === "水质杆") {
        return { width: 33, height: 45 };
      }
      if (type === "气象站") {
        return { width: 30, height: 42 };
      }
      if (type === "集中器") {
        return { width: 32, height: 40 };
      }
    },
    getOffset(type) {
      if (type === "大田杆" || type === "光伏大田杆") {
        return { width: 0, height: 75 }
      }
      if (type === "水质杆") {
        return { width: 0, height: 35 }
      }
      if (type === "气象站") {
        return { width: 0, height: 35 }
      }
      if (type === "集中器") {
        return { width: 0, height: 35 }
      }
    },
    getRisk(stau) {
      if (stau == 1) {
        return "低风险";
      }
      if (stau == 2) {
        return "中风险";
      }
      if (stau == 3) {
        return "高风险";
      }
      return "无风险"
    },
    getPestStyle(stau) {
      if (stau == 1) {
        return "#27F6ED";
      }
      if (stau == 2) {
        return "#F3EB73";
      }
      if (stau == 3) {
        return "#FB5055";
      }
    },
    queryCameraCount() {
      nowpagereq.countCamera({
        queryType: "3",
        facilityCategoryId: 1,
      }).then(res => {
        if (res.code == 200) {
          this.cameraCount = res.data || {}
        }
      })
    },
    async queryWeather() {
      let apiKey = '8187d1c02d1ba1cd0e808bce16674652'
      let location = `${this.center.lng},${this.center.lat}`
      const res = await axios.get(`https://restapi.amap.com/v3/geocode/regeo?key=${apiKey}&location=${location}&radius=1000&extensions=base&roadlevel=0`);

      const adcode = res.data.regeocode.addressComponent.adcode;
      const response = await axios.get(`https://restapi.amap.com/v3/weather/weatherInfo?key=${apiKey}&city=${adcode}`);
      this.weatherData = response.data.lives[0] || {}
      console.log(123, this.weatherData)
      // this.weatherData = res.data;
      // nowpagereq.queryWeather({
      //   url: `http://172.23.123.9:44102/weather?province=zhejiang&city=huzhou`,
      //   method: "get",
      //   loading: false
      // }).then(res => {
      //   if (res.code == 200) {
      //     this.weatherData = res.data || {}
      //   }
      // })
    },
    queryInsect(insectDeviceId) {
      nowpagereq.queryInsect({
        page: 1,
        size: 3,
        sortStr: "collectionTime",
        order: "desc",
        entity: {
          insectDeviceId,
        }
      }).then(res => {
        if (res.code == 1 && res.data && res.data.content && res.data.content[0]) {
          let list = res.data.content[0].insectCollectionResultList
          this.queryByInsectDeviceId(insectDeviceId, list)
          this.$set(this.insectData, `${insectDeviceId}time`, res.data.content[0].collectionTime)
        }
      })
    },
    queryByInsectDeviceId(insectDeviceId, list) {
      pestApi.queryByInsectDeviceId(insectDeviceId).then(res => {
        if (res.code === 1 && res.data.length) {
          list.map(el => {
            let row = res.data.find(ele => {
              return ele.pestId == el.insectTypedId
            })
            if (row) {
              if (el.insectNum >= row.lowRiskPestNumber) {
                let rishLevel = this.insectData[insectDeviceId] || 0
                rishLevel < 1 && this.$set(this.insectData, insectDeviceId, 1)
              }
              if (el.insectNum >= row.mediumRiskPestNumber) {
                let rishLevel = this.insectData[insectDeviceId] || 0
                rishLevel < 2 && this.$set(this.insectData, insectDeviceId, 2)
              }
              if (el.insectNum >= row.highRiskPestNumber) {
                let rishLevel = this.insectData[insectDeviceId] || 0
                rishLevel < 3 && this.$set(this.insectData, insectDeviceId, 3)
              }
              // console.log(el, this.insectData[insectDeviceId])
            }
          })
        }
      })
    },
    // 获取虫报站信息
    getInsectDevice() {
      insectApi.getinsectDevice().then(res => {
        this.pestList = res.data || []
        this.pestList.map(el => {
          this.queryInsect(el.insectDeviceId)
        })
      })
    },
    // 获取环境监测设备信息
    queryDevice() {
      deviceApi.dataItemlist({
        farming: "PLANT",
        systemNo: "MN",
        type: "物理",
        orgainzationMark: sessionStorage.organizationNo
      }).then(res => {
        if (res.code == 1) {
          this.deviceList = res.data.filter(el => {
            return el.axisX && el.axisY && el.deviceType
          })
        } else {
          this.deviceList = []
        }
      })
    },
    startVal(e) {
      // console.log(e)
    },
    endVal(e) {
      // console.log(e)
    },
    lesseeObj(e) {
      this.queryFacilityGroupList(e)
      this.getFacilityListByConditionAll()
    },
    // 信息窗体
    infoWindowClose(e) {
      this.infoWindow.show = false;
    },
    infoWindowOpen(e) {
      if (e) {
        this.lngLatCore = this.getCenterPoint(e);
        this.lngLatArrform = Object.assign(e[0].title);
        setTimeout(() => {
          this.infoWindow.show = true;
          // this.getdatatime()
        }, 100);
      }
    },
    infoWindowOot(e) {
      // this.infoWindow.show = false;
    },
    // 信息窗体
    infoMultipleClose(e) {
      this.infoMultiple.show = false;
    },
    infoMultipleOpen(e) {
      if (e) {
        // this.lngLatMultipleform = e
        this.lngLatMultipleCore = this.getCenterPoint(e);
        this.lngLatMultipleform = Object.assign(e[0].title);
        // console.log(this.lngLatMultipleCore);
        // console.log(this.lngLatMultipleform);
        this.pestInfoShow = false;
        this.deviceInfoShow = false;
        setTimeout(() => {
          this.infoMultiple.show = true;
          // this.getdatatime()
        }, 100);
      }
    },
    infoMultipleOut(e) {
      // this.infoMultiple.show = false;
    },
    caremaOpen(e) {
      console.log(e)
      this.cameralistparam = e[0].title;
      this.isShowCamera = true;
      setTimeout(() => {
        console.log(this.$refs.cameraDialog,e[0])
        this.$refs.cameraDialog.treeselectvalue(this.cameralistparam);
      }, 100);
    },
    deviceOpen(e) {
      if (e) {
        this.devicePint = { ...e }
        this.infoMultiple.show = false;
        this.pestInfoShow = false;
        this.deviceIotList = []
        deviceApi.queryLastDataByDeviceNos([e.deviceNo]).then(res => {
          if (res.code == 1) {
            let list = []
            res.data.map(el => {
              el.dataCollectNewVOList && el.dataCollectNewVOList.map(item => {
                if (item.enumListType) {
                  let arr = item.enumListType.split(';')
                  let obj = {}
                  arr.map(ele => {
                    let valList = ele.split(':')
                    obj[valList[0]] = valList[1]
                  })
                  item.lastValue1 = obj[item.lastValue1] || item.lastValue1
                }
                list.push({
                  ...item,
                  ...el
                })
              })
            })
            this.deviceIotList = list || []
          }
          this.$nextTick(() => {
            this.deviceInfoShow = true;
          });
        })
        this.deviceBtnList = []
        deviceApi.getalldataitemselect({
          control: true,
          // facilityNo: "JGDYC-068",
          deviceNo: e.deviceNo
        }).then(res => {
          if (res.code == 1) {
            this.deviceBtnList = res.data ? res.data.map((el, index) => {
              let item = { ...el }
              if (item.enumListType) {
                item["enumListTypetwo"] = this.handeltwo(item.enumListType);
              } else {
                this.$set(item, "enumListValue", 1);
              }
              this.getequipmentStau(item.dataItemId, index);
              return item
            }) : []
          } else {
            this.deviceBtnList = []
          }
          this.$nextTick(() => {
            this.deviceInfoShow = true;
          });
        })
      }
    },
    handeltwo(str) {
      var controlslist = [];
      var arr = str.split(";");
      for (var i = 0; i < arr.length; i++) {
        if (arr[i].length > 0) {
          var diy = arr[i].split(":");
          controlslist.push({
            name: diy[1],
            value: diy[0]
          });
        }
      }
      return controlslist;
    },
    // 获取机器状态
    getequipmentStau(id, index) {
      var data = {
        dataCollectNewId: id
      };
      nowpagereq.getshebeikiaguanstau(data).then(res => {
        if (res.data) {
          let value = res.data[0]?.lastValue1;
          this.$set(
            this.deviceBtnList[index],
            "enumListValue",
            value || 1
          );
          if (value === 0) {
            this.$set(this.deviceBtnList[index], "nowstau", "已关闭");
          }
          if (value === 1) {
            this.$set(this.deviceBtnList[index], "nowstau", "已开启");
          }
        } else {
          this.$set(this.deviceBtnList[index], "nowstau", "暂无数据");
        }
      });
    },
    pestOpen(e) {
      if (e) {
        this.pestPint = { ...e }
        this.infoMultiple.show = false;
        this.deviceInfoShow = false;
        this.pestIotList = []
        deviceApi.queryLastDataByDeviceNos([e.deviceNo]).then(res => {
          if (res.code == 1) {
            let list = []
            res.data.map(el => {
              el.dataCollectNewVOList && el.dataCollectNewVOList.map(item => {
                list.push({
                  ...item,
                  ...el
                })
              })
            })
            this.pestIotList = list || []
          }
          this.$nextTick(() => {
            this.pestInfoShow = true;
          });
        })
      }
    },
    // 获取机器状态,返回不同颜色
    getequipmentStyle(nowstau) {
      if (nowstau === "已关闭") {
        return "#ff0000";
      }
      if (nowstau === "已开启") {
        return "#00ff33";
      }
    },
    // 存储数据并且弹出验证码弹框
    controlequpmentone(id, key, indexone) {
      this.nowcontrolmessage = {
        zhid: id,
        zhkey: key,
        zhindex: indexone
      };
      this.openyanzhencode();
    },
    // 打开验证码弹框-重新获取验证码
    openyanzhencode() {
      this.nowcodetwo = "";
      this.yanzhengcodeview = true;
      // 获取随机的验证码和图片
      nowpagereq.getcodeimg().then(codres => {
        let listone = codres.data;
        if (listone) {
          this.nowcode = listone.stringCode;
          this.nowcodeimg = "data:image/png;base64," + listone.pictureData;
        }
      });
    },
    // 点击确认按钮
    yanzhengcode() {
      if (this.nowcodetwo === this.nowcode) {
        this.yanzhengcodeview = false;
        this.controlequpment();
      } else {
        this.$message.error("请输入正确的验证码");
      }
    },
    // 控制机器开关状态-------不可轻易调用
    controlequpment() {
      var params = {
        dataItemId: this.nowcontrolmessage.zhid,
        operation: parseInt(this.nowcontrolmessage.zhkey)
      };
      // console.log(params);

      // return;
      nowpagereq.setshebeikiaguanstau(params).then(res => {
        // 返回值需要确认下
        if (res.data) {
          this.$message.success("控制成功!");
        }
      });
      // 点击开关刷新状态,加五秒延迟
      var _that = this;
      setTimeout(function () {
        _that.getequipmentStau(
          this.nowcontrolmessage.zhid,
          this.nowcontrolmessage.zhindex
        );
      }, 5000);
    },
    // 条件查询所有设施组信息
    async queryFacilityGroupList(e) {
      const { data: res } = await landgroupInfoManage.getfacilityGroupAll({ lesseeNo: e || undefined });
      this.facilityGroupArr = res;
      // this.formItemList[0].options = res;
      this.$set(this.formItemList[0], 'selectOptions', res.map(el => {
        return { text: el.facilityGroupName, value: el.facilityGroupNo }
      }))
    },
    async querylesseeList() {
      // 获取承租人下拉框
      const { data: lessee } = await tenantInfo.queryLessesByCondition();
      this.lesseeList = lessee;
    },
    // 条件查询所有设施信息
    async getFacilityListByConditionAll() {
      let params = {
        facilityStatus: false,
        lesseeNo: this.lesseeNo
      };
      const { data: resp } =
        await divideInfoManage.getFacilityListByConditionAll(params);
      this.facilityArr = resp;
      // this.formItemList[1].options = resp;
      this.$set(this.formItemList[1], 'selectOptions', resp.map(el => {
        return { text: el.facilityName, value: el.facilityNo }
      }))
    },
    // 查询所有设施信息
    async FacilityPointList() {
      const { data: resp } = await divideInfoManage.queryAllFacilityDetail();
      // let facilityNameArr = resp;
      // console.log(resp)
      this.groupLngLatArr = [];
      let list = [];
      list = resp;
      this.facilityArr = resp;
      // this.formItemList[1].options = resp;
      this.$set(this.formItemList[1], 'selectOptions', resp.map(el => {
        return { text: el.facilityName, value: el.facilityNo }
      }))
      let lngLatAll = [];
      list.forEach((itemthree) => {
        if (itemthree.facilityPointList) {
          let lngLatArr = [];
          let facilityGroupArr = itemthree.facilityPointList;
          facilityGroupArr.forEach((item) => {
            const obj = {};
            obj["lng"] = item.axisY;
            obj["lat"] = item.axisX;
            obj["title"] = itemthree;
            lngLatArr.push(obj);
            lngLatAll.push(obj);
          });
          this.groupLngLatArr.push(lngLatArr);
          this.groupLngLatArr.forEach((item) => {
            item["center"] = this.getCenterPoint(item);
          });
          console.log(this.groupLngLatArr);
          // lngLatAll = this.groupLngLatArr[0] || [];
        }
      });
      let center = this.getCenterPoint(lngLatAll);
      // setTimeout(() => {
      if (lngLatAll.length) {
        this.$nextTick(() => {
          this.center = {
            lng: center.lng || 120.230648,
            lat: center.lat || 30.811543
          };
          this.queryWeather()
          if (this.groupLngLatArr.length >= 100) {
            this.zoom = 16;
            this.labelStyle.fontSize = "12px";
          } else if (
            this.groupLngLatArr.length >= 60 &&
            this.groupLngLatArr.length < 100
          ) {
            this.zoom = 17;
            this.labelStyle.fontSize = "12px";
          } else if (
            this.groupLngLatArr.length >= 15 &&
            this.groupLngLatArr.length < 60
          ) {
            this.zoom = 18;
            this.labelStyle.fontSize = "14px";
            // this.labelStyle.transform = "translateX(-15%)";
          } else if (this.groupLngLatArr.length < 15) {
            this.zoom = 18;
            this.labelStyle.fontSize = "16px";
            // this.labelStyle.transform = "translateX(0%)";
          }
        });
      } else {
        const { data: onInfo } =
          await divideInfoManage.queryonInfoByCondition();
        // console.log(onInfo)
        if (onInfo) {
          this.$set(this.center, "lng", onInfo.longitude);
          this.$set(this.center, "lat", onInfo.latitude);
          this.queryWeather()
        }
      }
      // }, 400);
      // console.log(this.list)
    },
    setCenterPoint({ type, target, point, pixel, overlay }) {
      this.center.lng = point.lng;
      this.center.lat = point.lat;
      // this.formData.latitude = point.lat;
      // this.formData.longitude = point.lng;
    },
    // 设施组下拉框改变时
    async facilityGroupChange() {
      let val = this.searchlist.facilityGroupNo
      if (!val) {
        this.groupLngLatArr = [];
        this.infoWindow.show = false;
        this.infoMultiple.show = false;
        this.lngLatArr = [];
        this.searchlist.facilityNo = "";
        this.search();
        this.getFacilityListByConditionAll();
        return;
      }
      this.groupLngLatArr = [];
      this.lngLatArr = [];
      this.infoWindow.show = false;
      this.infoMultiple.show = false;
      const { data: resp } = await landgroupInfoManage.queryFacilityGroup(val);
      let facilityGroupArr = resp;
      if (facilityGroupArr) {
        let facilityG = [];
        facilityGroupArr.forEach((itemthree) => {
          if (itemthree.facilityPointList) {
            facilityG.push(itemthree);
          }
          // if (itemthree.groupName) {
          //   this.facilityGName = itemthree.groupName
          // }
        });
        if (facilityG.length > 0) {
          let lngLatAll = [];
          facilityG.forEach(async (itemthree) => {
            let facilityPointList = itemthree.facilityPointList;
            // 获取 百度地图 经纬度
            let lngLatArr = [];
            facilityPointList.forEach((item) => {
              const obj = {};
              obj["lng"] = item.axisY;
              obj["lat"] = item.axisX;
              obj["title"] = itemthree;
              lngLatArr.push(obj);
              lngLatAll.push(obj);
            });
            this.groupLngLatArr.push(lngLatArr);
            this.groupLngLatArr.forEach((item) => {
              item["center"] = this.getCenterPoint(item);
            });
          });
          let center = this.getCenterPoint(lngLatAll);
          //  this.groupLngLatArr[0];
          // console.log(lngLatAll)
          // setTimeout(() => {
          if (lngLatAll.length) {
            this.$nextTick(() => {
              this.center = {
                lng: center.lng,
                lat: center.lat
              };
              if (this.groupLngLatArr.length > 100) {
                this.zoom = 16;
                this.labelStyle.fontSize = "12px";
              } else if (
                this.groupLngLatArr.length > 60 &&
                this.groupLngLatArr.length < 100
              ) {
                this.zoom = 17;
                this.labelStyle.fontSize = "14px";
              } else if (
                this.groupLngLatArr.length > 30 &&
                this.groupLngLatArr.length < 60
              ) {
                this.zoom = 18;
                this.labelStyle.fontSize = "16px";
                // this.labelStyle.transform = "translateX(-15%)";
              } else if (this.groupLngLatArr.length < 30) {
                this.zoom = 19;
                this.labelStyle.fontSize = "18px";
                // this.labelStyle.transform = "translateX(0%)";
              }
            });
          }
          // }, 200);
        } else {
          this.$message.warning("暂无设施组信息");
        }
      }
      if (val) {
        this.searchlist.facilityNo = "";
        this.facilityArr = facilityGroupArr;
        // this.formItemList[1].options = facilityGroupArr;
        this.$set(this.formItemList[1], 'selectOptions', facilityGroupArr.map(el => {
          return { text: el.facilityName, value: el.facilityNo }
        }))
      }
    },
    // 设施下拉框改变时
    async facilityChange() {
      let val = this.searchlist.facilityNo
      if (!val) {
        this.lngLatArr = [];
        this.infoWindow.show = false;
        this.infoMultiple.show = false;
        this.search();
        return;
      }
      this.lngLatArr = [];
      this.infoWindow.show = false;
      this.infoMultiple.show = false;
      const { data: res } = await divideInfoManage.queryFacilityById(val);
      let facilityPointList = res.facilityPointList;
      if (facilityPointList !== undefined) {
        facilityPointList.forEach((item) => {
          const obj = {};
          obj["lng"] = item.axisY;
          obj["lat"] = item.axisX;
          obj["title"] = res;
          // obj["title"]['groupName'] = this.facilityGName || ''
          this.lngLatArr.push(obj);
        });
        // this.lngLatArr.forEach(item => {
        //   item["center"] = this.getCenterPoint(item)
        // })
        this.$nextTick(() => {
          this.center = {
            lng: this.lngLatArr[0].lng,
            lat: this.lngLatArr[0].lat
          };
        });
      } else {
        return this.$message.warning("暂无设施信息");
      }
    },
    // 计算多边形中心点
    getCenterPoint(data) {
      let lng = 0.0;
      let lat = 0.0;
      // console.log(data)
      for (let point of data) {
        // console.log(point)
        lat += JSON.parse(point["lat"]);
        lng += JSON.parse(point["lng"]);
      }
      lng = lng / data.length + 0.000084;
      lat = lat / data.length + 0.000014;
      // console.log(lng, lat, data.length + 0.000084, data.length + 0.000014);
      return { lng: lng, lat: lat };
    },

    async search(data) {
      this.currentPage = 1;
      data && (this.searchlist = data)
      if (!this.searchlist.facilityGroupNo && !this.searchlist.facilityNo) {
        await this.FacilityPointList();
      } else {
        if (this.searchlist.facilityNo) {
          this.facilityChange();
        } else if (this.searchlist.facilityGroupNo) {
          this.facilityGroupChange();
        } else {
          this.facilityChange();
          this.facilityGroupChange();
        }
      }
    }
    // getdatatime() {
    //   let that = this;
    //   this.timer = setInterval(() => {
    //     // that.getdatatime(); // 声明一个变量指向Vue实例this，保证作用域一致
    //   }, 1000);
    // }
  }
};
</script>

<style scoped lang="scss">
@import "~@/styles/variables.scss";

.map {
  height: 100%;

  ::v-deep>div {
    >div {
      >div:nth-child(2) {
        >div:nth-child(2) {
          >div {
            color: aliceblue !important;
          }
        }
      }
    }
  }
}

.center {
  text-align: center;
  justify-content: center;
}

::v-deep .label {
  text-align: end;
  padding: 0 10px;
}

/*地图标题*/
::v-deep .BMap_bubble_title {
  width: 100%;
  font-size: 13px;
  font-weight: bold;
  text-align: center;
  justify-content: center;
  padding-bottom: 5px;
}

::v-deep {
  .BMap_bubble_content {
    background: rgba(2, 25, 3, 0.50) !important;
    color: #fff;
    position: relative;
    border-radius: 8px;

    &::after {
      content: '';
      width: 90px;
      height: 5px;
      background: #2EB0FC;
      position: absolute;
      top: -3px;
      left: calc(50% - 45px);
    }

    >div:nth-child(2) {
      >div:nth-child(2) {
        display: none;
      }
    }
  }

  .BMap_line {
    .BMap_line_title {
      width: 170px;
    }

    .BMap_line_time {
      width: 140px;
    }
  }
}

/* 内容 */
::v-deep .BMap_pop>div:nth-child(9) {
  top: 35px !important;
  border-radius: 7px;
}

/* 左上角删除按键 */
::v-deep .BMap_pop img {
  top: 40px !important;
  left: 5555px !important;
}

::v-deep .BMap_top {
  display: none;
}

::v-deep .BMap_bottom {
  display: none;
}

::v-deep .BMap_center {
  display: none;
}

/* 隐藏边角 */
::v-deep .BMap_pop {
  div:nth-child(1)>div {
    display: none;
  }

  div:nth-child(4) {
    display: none;
  }

  div:nth-child(3) {
    display: none;
  }

  div:nth-child(5) {
    display: none;
  }

  div:nth-child(7) {
    display: none;
  }

  div:nth-child(8) {
    display: none;
  }

  &>div:nth-child(9) {
    overflow: initial !important;
  }

  // div:nth-child(8) {
  // // background: cadetblue;
  // // height: 70px !important;
  // }
  //  div:nth-child(8)>img {
  // // display:none;
  // }
  .BMap_bubble_content {
    padding: 6px 10px 10px;

    p {
      display: flex;
      margin: 5px 0;

      span {
        min-width: 100px;
        // text-align: end;
      }
    }
  }
}

::v-deep .BMap_stdMpCtrl {
  inset: 45px 10px auto auto !important;
}

::v-deep .BMap_cpyCtrl {
  display: none;
}

::v-deep .BMap_shadow {
  display: none;
}

::v-deep .anchorBL {
  display: none;
}

::v-deep .BMap_Marker {
  div {
    // display: none;
  }
}

::v-deep .BMap_noprint {
  display: block;
}

::v-deep .BMap_cpyCtrl {
  display: none;
}

::v-deep .map {
  >div:first-child {
    >div:first-child {
      >div:nth-child(2) {
        div:nth-last-child(3) {
          display: none;
        }
      }
    }
  }
}

.camera-dialog {
  ::v-deep {
    .el-dialog {
      margin-top: 5vh;
      width: 1200px;

      .el-dialog__body {
        height: calc(100% - 55px) !important;
        max-height: calc(100% - 55px) !important;
        padding: 20px;
      }
    }
  }
}

::v-deep .yanzheng {
  .el-dialog {
    min-width: 20% !important;
    height: 30vh !important;
    // margin-top: 20vh !important;
    position: relative;

    .el-dialog__body {
      height: 18vh;
      padding-left: 50px !important;
    }
  }
}

// 验证码
.dig-yanzhencode {
  width: 100%;
  height: 100px;
  // background-color: #fff;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: center;
  text-align: center;

  .changecodeimg {
    width: 100%;
    margin-top: 2px;
    cursor: pointer;
    margin-bottom: 6px;
    white-space: nowrap;
    font-size: 13px;
    // color: #fff;
    // border-bottom: 1px solid rgb(26, 170, 175);
    color: rgb(26, 170, 175);
    border-color: rgb(26, 170, 175);
  }

  // .changecodeimg:hover {
  //   color: rgb(26, 170, 175);
  //   border-color: rgb(26, 170, 175);
  // }
}

.control-title {
  justify-content: center;
  position: relative;

  &::before {
    content: '';
    width: calc(50% - 50px);
    height: 1px;
    background: #fff;
    position: absolute;
    top: 8px;
    left: 10px;
  }

  &::after {
    content: '';
    width: calc(50% - 50px);
    height: 1px;
    background: #fff;
    position: absolute;
    top: 8px;
    right: 10px;
  }
}

.control-box {
  display: block !important;
  overflow: hidden;

  ::v-deep {
    .el-carousel__arrow--left {
      left: -12px !important;
      background: transparent;

      i {
        color: #5FB7F9;
      }
    }

    .el-carousel__arrow--right {
      right: -12px !important;
      background: transparent;

      i {
        color: #5FB7F9;
      }
    }
  }
}

.zh-contro {
  width: calc(100% - 40px);
  height: calc(100% - 10px);
  border-radius: 10px;
  border: 1px solid #0492FC;
  background: rgba(21, 91, 151, 0.59);
  margin: 5px 0 5px 18px;
  display: flex !important;
  flex-wrap: wrap;
  font-size: 13px;

  .contro-one {
    width: 100%;
    display: flex !important;
    justify-content: space-between;
    padding: 10px;

    .contro-one-title {
      font-size: 13px;
      width: calc(100% - 60px);
      overflow: hidden;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
    }

    .contro-one-stau {
      display: inline-block !important;
      font-size: 13px;
      width: 60px;
    }
  }

  .contro-two {
    width: 250px;
    display: flex !important;
    justify-content: space-around;
    align-items: flex-start;
    position: relative;

    .contro-two-zcon {
      border: solid 1px #00718f;
      height: 30px;
      width: 70px;
      line-height: 28px;
      text-align: center;
      font-size: 13px;
      border-radius: 15px;
      cursor: pointer;
      background: linear-gradient(180deg, #76f5d2 0%, #0098b7 100%);
      color: #fff;
    }

    .contro-two-zcon-disabled {
      border: solid 1px #00718f;
      height: 30px;
      width: 70px;
      line-height: 28px;
      text-align: center;
      font-size: 13px;
      border-radius: 15px;
      cursor: not-allowed;
    }

    // .contro-two-zcon:hover {
    //   background: linear-gradient(180deg, #76f5d2 0%, #0098b7 100%);
    //   color: #fff;
    // }
    .contro-two-zcon-select {
      background-color: #fff;
      color: #003947;
    }

    .contro-two-zcons {
      background-color: #fff;
      color: #003947;
    }

    .inputnumber {
      width: 70px;
      border-radius: 10rpx;
    }

    .unit {
      position: absolute;
      top: 15px;
      left: 95px;
    }
  }
}

.weather {
  width: 100%;
  line-height: 36px;
  background: #38436d;
  z-index: 99;
  text-align: center;
  color: #ffffff;
  margin-bottom: 14px;

  img {
    width: 25px;
    height: 25px;
    vertical-align: middle;
    margin-right: 15px;
  }

  span {
    display: inline-block;
    margin-right: 35px;
    vertical-align: middle;

    &:last-child {
      margin-right: 0;
    }
  }
}

.checkbox-box {
  position: absolute;
  bottom: 50px;
  right: 40px;
  z-index: 9;

  ::v-deep {
    .el-checkbox {
      display: block;
      margin: 0 0 5px 0 !important;
    }

    .el-checkbox__label {
      color: #fff;
    }
  }
}

.tableSlot {
  .map {
    height: calc(100% - 55px);
  }
}
</style>
